package com.yanggeng.demo.beginnerguidedemo.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.help.Tip;
import com.wlwl.os.listbottomsheetdialog.MyDecoration;
import com.wlwl.os.listbottomsheetdialog.OnItemClickListener;
import com.yanggeng.demo.beginnerguidedemo.R;
import com.yanggeng.demo.beginnerguidedemo.TestApplication;
import com.yanggeng.demo.beginnerguidedemo.adapter.LocationListAdapter;
import com.yanggeng.demo.beginnerguidedemo.bean.EventConstant;
import com.yanggeng.demo.beginnerguidedemo.bean.EventMessage;
import com.yanggeng.demo.beginnerguidedemo.widget.MyBottomSheepDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by yanggeng on 2017/9/15.
 */

public class MapActivity extends BaseActivity implements LocationSource, AMapLocationListener, AMap.OnMarkerClickListener {

    private MapView mapView;
    private AMap aMap;
    private MyLocationStyle myLocationStyle;
    private TextView tvSearch;
    private Context context;
    private static final int REQUEST_CODE_SEARCH = 0x101;
    OnLocationChangedListener mListener;
    AMapLocationClient mlocationClient;
    AMapLocationClientOption mLocationOption;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);
        context = this;
        EventBus.getDefault().register(this);
        hideToolbar();
        mapView = (MapView) findViewById(R.id.map);
        tvSearch = (TextView) findViewById(R.id.tv_search);
        tvSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(context, LocationSearchActivity.class), REQUEST_CODE_SEARCH);
            }
        });
        findViewById(R.id.ib_location).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
                LatLng latLng = TestApplication.getApplication().getCurrLatLng();
                aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));
            }
        });
        mapView.onCreate(savedInstanceState);

        if (aMap == null) {
            aMap = mapView.getMap();
        }
//        aMap.setLocationSource(this);
        aMap.getUiSettings().setMyLocationButtonEnabled(false);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
        myLocationStyle = new MyLocationStyle();
//        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW);
        myLocationStyle.interval(2000);
        myLocationStyle.strokeColor(Color.TRANSPARENT);
        myLocationStyle.radiusFillColor(Color.TRANSPARENT);
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.setMyLocationEnabled(true);
        LatLng latLng = TestApplication.getApplication().getCurrLatLng();
//        aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));

//        MarkerOptions options = new MarkerOptions();
//        options.position(latLng);
//        options.title(TestApplication.getApplication().getAddress());
//        aMap.addMarker(options);
        //设置定位蓝点显示

        aMap.setOnMarkerClickListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        EventBus.getDefault().unregister(this);
        if (null != mlocationClient) {
            mlocationClient.onDestroy();
        }
    }

    @Override
    public void onClick(View v) {
       if (v == iv_cancel) {
           if (popupWindow != null && popupWindow.isShowing()) {
               popupWindow.dismiss();
           } else {
               finish();
           }
       }
    }

    @Override
    public void onBackPressed() {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
        dismissPopWindow();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    public void activate(LocationSource.OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        if (mlocationClient == null) {
            //初始化定位
            mlocationClient = new AMapLocationClient(this);
            //初始化定位参数
            mLocationOption = new AMapLocationClientOption();
            //设置定位回调监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();//启动定位
        }
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_SEARCH) {
            if (data != null) {
                ArrayList<PoiItem> poiItems = (ArrayList<PoiItem>) data.getSerializableExtra("data");
                if (poiItems != null && poiItems.size() > 0) {
                    aMap.clear();
                    Log.e("poiItems", "not null");
                    aMap.moveCamera(CameraUpdateFactory.zoomTo(15));
                    LatLng latLng = TestApplication.getApplication().getCurrLatLng();
//                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));
                    for (PoiItem poiItem :
                            poiItems) {
                        aMap.addMarker(new MarkerOptions()
                                .position(new LatLng(poiItem.getLatLonPoint().getLatitude(), poiItem.getLatLonPoint().getLongitude()))
                                .title(poiItem.getTitle()).snippet(poiItem.getSnippet()));
                    }
                    dismissPopWindow();
                    showBottomSheetDialog(poiItems);
                } else {
                    Log.e("poiItems", "null");
                }
            }
        }
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mListener != null && aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
//                mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
            } else {
                String errText = "定位失败," + aMapLocation.getErrorCode() + ": " + aMapLocation.getErrorInfo();
                Log.e("AmapErr", errText);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventMessage event) {
        switch (event.getTagEvent()) {
            case EventConstant.SEARCH_LOCATION:
                Tip tip = (Tip) event.getObject();
                aMap.clear();
                dismissPopWindow();
                LatLng latLng = new LatLng(tip.getPoint().getLatitude(), tip.getPoint().getLongitude());
                aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));
                aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
                aMap.addMarker(new MarkerOptions().position(latLng).title(tip.getName() + "\n" + tip.getAddress()));
                float distance = AMapUtils.calculateLineDistance(new LatLng(tip.getPoint().getLatitude(), tip.getPoint().getLongitude()), TestApplication.getApplication().getCurrLatLng());
                showPopWindow(tip.getName(), distance + "米", tip.getAddress(), new LatLng(tip.getPoint().getLatitude(), tip.getPoint().getLongitude()));
                break;
        }
    }

    private MyBottomSheepDialog myBottomSheepDialog;
    private TextView tvName, tvDistance, tvAddress;
    private ImageView ivGo;
    private RecyclerView rvLocations;
    private LocationListAdapter listAdapter;

    private void showBottomSheetDialog(final List<PoiItem> poiItems) {
        if (myBottomSheepDialog == null) {
            myBottomSheepDialog = new MyBottomSheepDialog(context);
            View view = LayoutInflater.from(context).inflate(R.layout.layout_recycleview, null);
            rvLocations = (RecyclerView) view.findViewById(R.id.recycle_view);
            listAdapter = new LocationListAdapter(context, poiItems);
            rvLocations.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
            rvLocations.addItemDecoration(new MyDecoration(context));
            rvLocations.setAdapter(listAdapter);
            myBottomSheepDialog.setContentView(view);
            myBottomSheepDialog.setCanceledOnTouchOutside(true);
            myBottomSheepDialog.setCancelable(true);
            myBottomSheepDialog.setOnShowListener(new DialogInterface.OnShowListener() {
                @Override
                public void onShow(DialogInterface dialog) {
                    WindowManager.LayoutParams params = getWindow().getAttributes();
                    params.alpha = 1.0f;
                    getWindow().setAttributes(params);
                }
            });
        }
        listAdapter.notifyData(poiItems);
        listAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int i) {
                PoiItem poiItem = poiItems.get(i);
                showPopWindow(poiItem.getTitle(), AMapUtils.calculateLineDistance(TestApplication.getApplication().getCurrLatLng(),
                        new LatLng(poiItem.getLatLonPoint().getLatitude(), poiItem.getLatLonPoint().getLongitude())) + "米", poiItem.getSnippet(),
                        new LatLng(poiItem.getLatLonPoint().getLatitude(), poiItem.getLatLonPoint().getLongitude()));

                myBottomSheepDialog.dismiss();
            }
        });
        if (!myBottomSheepDialog.isShowing()) {
            myBottomSheepDialog.show();
        }

    }

    private PopupWindow popupWindow;
    private void showPopWindow(final String name, String distance, String address, final LatLng latLng) {
        if (popupWindow == null) {
            View view = LayoutInflater.from(context).inflate(R.layout.layout_location_item, null);
            tvName = (TextView) view.findViewById(R.id.tv_name);
            tvDistance = (TextView) view.findViewById(R.id.tv_distance);
            tvAddress = (TextView) view.findViewById(R.id.tv_address);
            ivGo = (ImageView) view.findViewById(R.id.iv_go);
            popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            popupWindow.setOutsideTouchable(true);
        }
        tvName.setText(name);
        tvDistance.setText(distance);
        tvAddress.setText(address);
        ivGo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                ToastUtil.centerToast(context, "跳转到地图APP");
//                PackageManagerUtil.toMapApp(context, latLng.latitude, latLng.longitude, name);
                Intent intent = new Intent(context, MapNaviActivity.class);
                intent.putExtra("startLatLng", TestApplication.getApplication().getCurrLatLng());
                intent.putExtra("endLatLng", latLng);
                startActivity(intent);
            }
        });
        if (!popupWindow.isShowing()) {
            popupWindow.showAtLocation(main_view, Gravity.BOTTOM, 0, 0);
        }

    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        float distance = AMapUtils.calculateLineDistance(marker.getPosition(), TestApplication.getApplication().getCurrLatLng());
        showPopWindow(marker.getTitle(), distance + "米", marker.getSnippet(), marker.getPosition());
        return false;
    }

    private void dismissPopWindow() {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
    }
}
